package cn.edu.lingnan.springbootlingnanblog.controller;

import cn.edu.lingnan.springbootlingnanblog.entity.Blogger;
import cn.edu.lingnan.springbootlingnanblog.service.BloggerService;
import cn.edu.lingnan.springbootlingnanblog.utils.DateUtil;
import cn.edu.lingnan.springbootlingnanblog.utils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (TBlogger)表控制层
 *
 * @author makejava
 * @since 2020-06-13 08:34:08
 */
@Controller
@RequestMapping("blogger")
public class BloggerController {
    /**
     * 服务对象
     */
    @Resource
    private BloggerService BloggerService;

    @PostMapping("login")
    public String login(String name, String password, Model model, HttpSession session){
        System.out.println("login:::name:::" + name + ", password:::" + password);
        Blogger Blogger = BloggerService.login(name, password);
        if (Blogger == null){
            model.addAttribute("msg", "用户名或者密码错误！");

            return "login";
        }else {
            model.addAttribute("loginUser", Blogger.getName());
            session.setAttribute("loginBlogger", Blogger);
            return "/admin/main";
        }
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ResponseBody
    public Blogger selectOne(Integer id) {
        return this.BloggerService.queryById(id);
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }


    @RequestMapping("toReg")
    public String toReg(){
        return "register";
    }
    @PostMapping("reg")
    public String reg(@Valid Blogger bean, BindingResult br, String cfmpassword, Model model) {
        System.out.println("reg:::" + bean);
        System.out.println("reg:::" + cfmpassword);
        //判断两次密码是否一致
        if(!bean.getPassword().equals(cfmpassword)) {
            model.addAttribute("msg", "两次输入密码不一致");
            return "register";
        }
        //数据较验
        if(br.hasErrors()) {
            Map<String, String> errors = new HashMap<String, String>();
            System.out.println("==============================表单数据出错=================================");
            List<FieldError> fieldErrors = br.getFieldErrors();
            for (FieldError item : fieldErrors) {
                System.out.println(item.getField());
                System.out.println(item.getDefaultMessage());
                errors.put(item.getField(), item.getDefaultMessage());
            }
            model.addAttribute("errors", errors);
            return "register";
        }

        //判断用户名重复
        if (BloggerService.getByName(bean.getName()) != null) {
            model.addAttribute("msg", "该用户名已经被使用");
            return "register";
        }

        boolean result = BloggerService.insert(bean);
        if (result) {
            System.out.println("注册成功");
            return "login";
        }
        System.out.println("注册失败");
        model.addAttribute("msg", "注册失败");
        return "register";
    }

    @RequestMapping("/save")
    public String save(@RequestParam("imageFile") MultipartFile imageFile, Blogger blogger, Model model,
                       BindingResult br, HttpServletRequest request, HttpServletResponse response)throws Exception{
        if(!imageFile.isEmpty()){
            String filePath=request.getServletContext().getRealPath("/");
            String imageName= DateUtil.getCurrentDateStr()+"."+imageFile.getOriginalFilename().split("\\.")[1];
            imageFile.transferTo(new File("C:\\Users\\Administrator\\Desktop\\springboot-lingnanblog\\src\\main\\resources\\static\\userImages/"+imageName));
            blogger.setImageName(imageName);
        }
        System.out.println(blogger);
        boolean resultTotal=BloggerService.update(blogger);
        System.out.println(resultTotal);
        StringBuffer result=new StringBuffer();
        if(resultTotal){
            result.append("<script language='javascript'>alert('修改成功');</script>");
        }else{
            result.append("<script language='javascript'>alert('修改失败');</script>");
        }
        ResponseUtil.write(response, result);
        return null;
    }


    @RequestMapping("toEdit")
    public String toEdit(Model model){
        return "admin/modifyInfo";
    }

}